import requests
import re, time
import operator
from bs4 import BeautifulSoup
from bs4.element import NavigableString 
import tkinter as tk
from tkinter import ttk
import pyperclip

class Currency_GUI:
    def __init__(self):
        self.gcr=Get_Currency_Rate()
        self.rategroup_list =[]
        self.interval = 600000
        self.win = tk.Tk()    # 实例化object，建立窗口window
        self.win.title('Currency Rate')  # 第2步，给窗口的可视化起名字
        self.win.geometry('900x400')  # # 第3步，设定窗口的大小(长 * 宽)   这里的乘是小x

        #标签
        ttk.Label(self.win,text="刷新间隔(秒)").grid(row=0,column=3,sticky=tk.E)

        #时间标签
        time_text = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        self.time_label = ttk.Label(self.win,text=time_text)
        self.time_label.grid(row=0,column=5,sticky=tk.E)

        #下拉框
        self.comvalue=tk.StringVar()#窗体自带的文本，新建一个值
        self.comboxlist=ttk.Combobox(self.win,width=5,textvariable=self.comvalue) #初始化
        self.comboxlist["values"]=("30","60","120","300","600")
        self.comboxlist.current(4)  #选择第5个值
        self.comboxlist.bind("<<ComboboxSelected>>",self.set_interval)  #绑定事件
        self.comboxlist.grid(row=0,column=4,sticky=tk.W,padx=5)

        #表格1
        self.tree1=ttk.Treeview(self.win,height=7,show="headings")
        self.tree1.grid(row=1,column=0,columnspan=8,padx=5)
        self.tree1.bind("<Double-Button-1>", self.get_item)    #绑定双击事件
        self.def_tree(self.tree1)
        #给表格1添加数据
        self.refresh_data()
        
        #表格2
        self.tree2=ttk.Treeview(self.win,height=7,show="headings")
        self.tree2.grid(row=3,column=0,columnspan=8,padx=5)
        self.def_tree(self.tree2)

        #复制数据按钮，复制表格1数据 --> 表格2
        tk.Button(self.win, text ="复制数据", command = self.CopyData).grid(row=2,column=3,sticky=tk.E)

        # 主窗口循环显示
        self.win.mainloop()

    def def_tree(self,tree):
        #定义列
        tree["columns"]=('币种','银行','现汇卖出','现钞卖出','现汇买入','现钞买入','时间','URL')
        #设置列属性，列不显示
        tree.column("币种",width=80,anchor='center')
        tree.column("银行",width=80,anchor='center')
        tree.column("现汇卖出",width=80,anchor='e')
        tree.column("现钞卖出",width=80,anchor='e')
        tree.column("现汇买入",width=80,anchor='e')
        tree.column("现钞买入",width=80,anchor='e')
        tree.column("时间",width=80,anchor='e')
        tree.column("URL",width=300,stretch = True)
    
        #设置表头
        tree.heading("币种",text="币种")
        tree.heading("银行",text="银行")
        tree.heading("现汇卖出",text="现汇卖出")
        tree.heading("现钞卖出",text="现钞卖出")
        tree.heading("现汇买入",text="现汇买入")
        tree.heading("现钞买入",text="现钞买入")
        tree.heading("时间",text="时间")
        tree.heading("URL",text="URL")

    def refresh_data(self):
        self.time_label['text'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())   #刷新取数据时间

        self.rategroup_list = self.gcr.boc_rate()      #取汇率数据
        self.rategroup_list.extend(self.gcr.icbc_rate())
        self.rategroup_list.extend(self.gcr.cmb_rate())      

        rg_list = self.rategroup_list
        for item in self.tree1.get_children():
            self.tree1.delete(item)       #先清空
        for i in range(len(rg_list)):
            self.tree1.insert("",i,text="",values=(rg_list[i][0],rg_list[i][1],rg_list[i][2],rg_list[i][3],rg_list[i][4],rg_list[i][5],rg_list[i][6],rg_list[i][7]))  
        self.tree1.after(self.interval,self.refresh_data)   #定时刷新

    def get_item(self,*args):    #复制tree中被点击的行到剪贴板
        for item in self.tree1.selection():
            item_text = self.tree1.item(item,"values")
            pyperclip.copy(','.join(item_text))

    def CopyData(self):
        rg_list = self.rategroup_list
        for item in self.tree2.get_children():
            self.tree2.delete(item)       #先清空
        for i in range(len(rg_list)):
            self.tree2.insert("",i,text="",values=(rg_list[i][0],rg_list[i][1],rg_list[i][2],rg_list[i][3],rg_list[i][4],rg_list[i][5],rg_list[i][6],rg_list[i][7]))  

    def set_interval(self,*args):   #处理事件，*args表示可变参数
        self.interval = int(self.comboxlist.get())*1000    #修改刷新间隔的值

class Get_Currency_Rate():    
    def __init__(self):
        self.currency_list=['美元','卢布']

    def icbc_rate(self):
        url = 'http://www.icbc.com.cn/ICBCDynamicSite/Optimize/Quotation/QuotationListIframe.aspx'
        r = requests.get(url,timeout=3)
        #print(r.text)
    
        bs = BeautifulSoup(r.text,"html.parser")
        data_list = bs.find_all(class_="tdCommonTableData")
        rategroup_list = []
        if data_list:
            #print(data_list)
            i = 0 
            while i < len(data_list):
                for curr in self.currency_list:
                    if str(data_list[i].string).find(curr) >= 0:   #'美元(USD)','卢布(RUB)'
                        rate_list = []
                        rate_list.append(curr)
                        rate_list.append('工商银行')
                        rate_list.append(data_list[i+3].string)    #现汇卖出
                        rate_list.append(data_list[i+4].string)    #现超卖出
                        rate_list.append(data_list[i+1].string)    #现汇买入
                        rate_list.append(data_list[i+2].string)    #现钞买入
                        rate_list.append(data_list[i+5].string.split(' ')[1])    #时间 2020年03月19日 10:18:44
                        rate_list.append(url)                          #url
                        rategroup_list.append(rate_list)
                        i += 6
                    else:
                        i += 1            
        #print(rategroup_list)
        return rategroup_list
    
    def boc_rate(self):
        url = 'https://www.boc.cn/sourcedb/whpj/'
        r = requests.get(url,timeout=3)
        htmlpage = r.content.decode('utf-8')
    
        bs = BeautifulSoup(htmlpage,"html.parser")
        td_list = bs.find_all("td")
        i = 0
        rategroup_list = []
        if td_list:
            #print(td_list)
            i = 0 
            while i < len(td_list):
                if td_list[i].string  in  self.currency_list:   #'美元','卢布'
                    rate_list = []
                    rate_list.append(td_list[i].string)
                    rate_list.append('中国银行')
                    rate_list.append(td_list[i+3].string)    #现汇卖出
                    rate_list.append(td_list[i+4].string)    #现超卖出
                    rate_list.append(td_list[i+1].string)    #现汇买入
                    rate_list.append(td_list[i+2].string)    #现钞买入
                    rate_list.append(td_list[i+7].string)    #时间  10:18:44
                    rate_list.append(url)                          #url
                    rategroup_list.append(rate_list)
                    i += 7
                else:
                    i += 1   
        #print(rategroup_list)
        return rategroup_list
    
    def cmb_rate(self):
        url = 'http://fx.cmbchina.com/Hq/'
        r = requests.get(url,timeout=3)
        bs = BeautifulSoup(r.text,"html.parser")
        data_list = bs.find(class_="data")
        count = -1
        rategroup_list = []
        for item in  data_list.children:
            if type(item) == NavigableString:
                #print(item.get_text())
                continue
            rate_list = []
            for item1 in item.children:
                if type(item1) == NavigableString :
                    continue
                rate = str(item1.string).strip()
                if rate == '美元' or rate == '欧元':
                    rate_list.append(rate)
                    rate_list.append('招商银行')
                    count = 0
                if count >= 0:
                   count += 1
                if count >= 4  and count <= 8:
                    rate_list.append(rate)
            if len(rate_list) > 0:
                rate_list.append(url)
                rategroup_list.append(rate_list)
        #print(rategroup_list)
        return rategroup_list
    
    def print_ExchangeRate(self):
        self.rategroup_list = self.boc_rate()
        self.rategroup_list.extend(self.icbc_rate())
        self.rategroup_list.extend(self.cmb_rate())
        
        self.rategroup_list.sort(key=operator.itemgetter(0))
        print('%10s%10s%10s%10s%10s%10s%10s%10s'%('币种','银行','现汇卖出','现钞卖出','现汇买入','现钞买入','时间','URL'))
        for data_list in self.rategroup_list:
            for item in data_list:
                print('%10s'%item,end=' ')
            print()
    
if __name__ == '__main__':
    #Get_Currency_Rate().print_ExchangeRate()
    Currency_GUI()
    